package org.jeecg.modules.demo.Kingdee.BankacntState;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static org.jeecg.modules.demo.util.KingdeeUtil.cleanExcelFormats;
import static org.jeecg.modules.demo.util.KingdeeUtil.convertExcelToMapListNormal;

/**
 * RPA下载的文件自动导入银行对账单
 *
 * @Author Scott
 */
@Slf4j
@Component
public class ImportBankacntStateJob implements Job {
    @SneakyThrows
    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        // 获取当前时间（时分秒）
        LocalTime currentTime = LocalTime.now();
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 定义日期格式（yyyy-MM-dd）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate targetDate;
        // 判断是否为上午（12点前）
        if (currentTime.isBefore(LocalTime.NOON)) { // LocalTime.NOON 表示 12:00:00
            // 上午：取前一天
            targetDate = currentDate.minusDays(1);
        } else {
            // 下午（含12点）：取当天
            targetDate = currentDate;
        }

        // 格式化为字符串
        String result = targetDate.format(formatter);
        System.out.println("目标日期：" + result);

        String filePath = "C:\\BankacntState\\bankacntState.xlsx";
        String outputPath = "C:\\BankacntState\\"+UUID.randomUUID()+".xlsx"; // 输出文件路径
        cleanExcelFormats(filePath, outputPath);
//
        File file = new File(outputPath);
        if (!file.exists()) {
            log.error("文件[" + outputPath + "]不存在..");
            return;
        }
        K3CloudApi api = new K3CloudApi();
        List<Map<String, Object>> list = convertExcelToMapListNormal(outputPath, 0, 1, false, 0);
        List<Map> newList = new ArrayList<>();
        // 定义格式：只关注年月日部分（忽略时分）
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        for (Map<String, Object> item : list) {
            String dateStr = item.get("交易时间").toString();
            LocalDate dateStrL = LocalDate.parse(dateStr, formatter1);
            // 3. 比较日期是否相同
            boolean isSameDate = dateStrL.equals(targetDate);
            if (!isSameDate) {
                continue;
            }
            String index = item.get("余额（元）") + "-" + item.get("交易时间");
//			查询金蝶对账单中有无此数据
            String json = "{\n" +
                    "    \"FormId\": \"CN_BANKACNTSTATE\",\n" +
                    "    \"FieldKeys\": \"FID\",\n" +
                    "    \"FilterString\": \"FACCOUNTINGSERIALNO ='" + index + "'\",\n" +
                    "}";
            int size = JSONArray.parseArray(api.billQuery(json)).size();
            if (!(size > 0)) {
                newList.add(item);
            }
        }
        if (newList.isEmpty()) {
            return;
        }
        JSONArray pre = new JSONArray();
        for (Map<String, String> item : newList) {
            String index = item.get("余额（元）") + "-" + item.get("交易时间");
            String type = item.get("交易类型");
            JSONObject preitem = new JSONObject();
            if (type.equals("收入")) {
//			收入
                preitem.put("FCREDITAMOUNT", item.get("交易金额（元）"));
            } else {
//			支出
                preitem.put("FDEBITAMOUNT", item.get("交易金额（元）"));
            }
            preitem.put("FTRANSDATE", item.get("交易时间"));
//			preitem.put("FOPPOSITEBANKNAME", item.get("对方开户行"));
            preitem.put("FOPPOSITEBANKACNTNO", item.get("对方账号"));
            preitem.put("FOPPOSITECCOUNTNAME", item.get("对方户名"));
            preitem.put("FACCOUNTINGSERIALNO", index);
            preitem.put("FEXPLANATION", item.get("用途"));
            pre.add(preitem);
        }
        Collections.reverse(pre);
//		String now = DateUtils.now();
        String json = "{\n" +
                "    \"NeedUpDateFields\": [],\n" +
                "    \"NeedReturnFields\": [],\n" +
                "    \"IsDeleteEntry\": \"true\",\n" +
                "    \"SubSystemId\": \"\",\n" +
                "    \"IsVerifyBaseDataField\": \"false\",\n" +
                "    \"IsEntryBatchFill\": \"true\",\n" +
                "    \"ValidateFlag\": \"true\",\n" +
                "    \"NumberSearch\": \"true\",\n" +
                "    \"IsAutoAdjustField\": \"true\",\n" +
                "    \"InterationFlags\": \"\",\n" +
                "    \"IgnoreInterationFlag\": \"\",\n" +
                "    \"IsControlPrecision\": \"false\",\n" +
                "    \"ValidateRepeatJson\": \"false\",\n" +
                "    \"Model\": {\n" +
                "        \"FID\": 0,\n" +
                "        \"FBANKID\": {\n" +
                "            \"FNumber\": \"001\"\n" +
                "        },\n" +
                "        \"FBANKACNTID\": {\n" +
                "            \"FNumber\": \"44001646439053005541\"\n" +
                "        },\n" +
                "        \"FCurrencyId\": {\n" +
                "            \"FNumber\": \"PRE001\"\n" +
                "        },\n" +
                "        \"FBEGINDATE\": \"" + result + "\",\n" +
                "        \"FENDDATE\": \"" + result + "\",\n" +
                "        \"FEntity\": " + pre.toJSONString() +
                "    }\n" +
                "}";
        String saveJson = api.save("CN_BANKACNTSTATE", json);
        JSONObject ResponseStatus = JSON.parseObject(saveJson).getJSONObject("Result").getJSONObject("ResponseStatus");
        JSONObject successEntitys = ResponseStatus.getJSONArray("SuccessEntitys").getJSONObject(0);
//			暂存的单据id
        String Id = successEntitys.getString("Id");
        String Auditjson = String.format("{\"Ids\": \"%s\"}", Id);
        String submitResult = api.submit("CN_BANKACNTSTATE", Auditjson);
        String auditResult = api.audit("CN_BANKACNTSTATE", Auditjson);
        log.info("审核银行账单结果："+auditResult);
    }
}
